const activityModel = require("../../models/sys/activity");
const axios = require('axios');
const { wechatConfig } = require('../../config/index');
const { formatTime } = require('../../utils/utils');

module.exports = {
  // 获取活动列表
  async list(req, res) {
    let { currentPage, pageSize } = req.query;
    currentPage = parseInt(currentPage);
    pageSize = parseInt(pageSize);
    console.log("活动列表参数", currentPage, pageSize);
    const startIndex = (currentPage - 1) * pageSize;

    if (!currentPage || !pageSize) {
      return res.json({
        code: "1001",
        msg: "参数错误",
      });
    }

    const resp = await activityModel.list([startIndex, pageSize]);
    // console.log('查询活动列表：', resp);

    res.json({
      code: "200",
      msg: "ok",
      data: resp,
    });
  },
  async check(req, res) {
    const { state, id, openid, activityTitle, activityTime } = req.body;
    try {
      const resp = await activityModel.check([state, id]);
      console.log('活动审核数据库结果：', resp);

      const getAccessTokenRes = await axios({
        url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential',
        method: 'GET',
        params: {
          appid: wechatConfig.appid,
          secret: wechatConfig.appsecret
        }
      });
      console.log('获取凭证成功：', getAccessTokenRes.data);

      //  时间处理
      const time3 = formatTime(activityTime);
      const time11 = formatTime(new Date());
      console.log(time11, '时间time3', time3);

      const subscribeResp = await axios({
        url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + getAccessTokenRes.data.access_token,
        method: 'POST',
        data: {
          touser: openid, // 接收者（用户）的 openid
          template_id: "tpmcb82V9DO3oH-EWkiQmS-pg1jJfiZmX90Yz63JhxU", // 所需下发的订阅模板id
          // page: "index", // 点击模板卡片后的跳转页面
          // miniprogram_state: "developer", // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
          // lang: "zh_CN", // 进入小程序查看”的语言类型
          data: { // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
            "phrase1": {
              "value": "通过"
            },
            "thing2": {
              "value": activityTitle
            },
            "time3": {
              "value": time3
            },
            "time11": {
              "value": time11
            }
          }
        }
      });
      console.log('订阅消息通知：', subscribeResp.data);

      res.json({
        code: '200',
        msg: '审核成功'
      });

    } catch (err) {
      console.log('活动审核出错：', err);
      res.json({
        code: '1001',
        msg: '请求错误'
      })
    }
  }
}